<template>
  <div class="user-recycle-type-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
          v-model="searchForm.keyword"
          placeholder="请输入废品类型"
          style="width: 200px; margin-right: 10px;"
          clearable
      ></el-input>
      <el-button type="primary" @click="searchTypes">搜索</el-button>
    </div>

    <!-- 废品类型列表 -->
    <div class="type-list">
      <el-row :gutter="20">
        <el-col :span="8" v-for="type in typeList" :key="type.id">
          <el-card class="type-card" shadow="hover">
            <div class="type-header">
              <h3>{{type.typeName}}</h3>
              <el-tag type="success">¥{{type.price}}/{{type.unit}}</el-tag>
            </div>
            <div class="type-content">
              <p class="description">{{type.description || '暂无描述'}}</p>
              <div class="unit-info">
                <i class="el-icon-info"></i>
                <span>计量单位：{{type.unit}}</span>
              </div>
            </div>
            <div class="type-footer">
              <el-button type="primary" @click="createOrder(type)">立即预约</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 预约弹窗 -->
    <el-dialog title="预约回收" :visible.sync="orderDialogVisible" width="500px">
      <el-form :model="orderForm" :rules="orderRules" ref="orderForm" label-width="100px">
        <el-form-item label="废品类型">
          <span>{{currentType.typeName}}</span>
        </el-form-item>
        <el-form-item label="预估重量" prop="weight">
          <el-input-number v-model="orderForm.weight" :min="0" :precision="2" style="width: 100%"></el-input-number>
          <span class="unit">{{currentType.unit}}</span>
        </el-form-item>
        <el-form-item label="回收地址" prop="address">
          <el-input type="textarea" v-model="orderForm.address"></el-input>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
              v-model="orderForm.appointmentTime"
              type="datetime"
              placeholder="选择预约时间"
              style="width: 100%"
              :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="orderForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOrder">确认预约</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserRecycleType',
  data() {
    return {
      searchForm: {
        keyword: ''
      },
      typeList: [],
      orderDialogVisible: false,
      currentType: null,
      orderForm: {
        weight: 0,
        address: '',
        appointmentTime: '',
        remark: ''
      },
      orderRules: {
        weight: [
          { required: true, message: '请输入预估重量', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入回收地址', trigger: 'blur' }
        ],
        appointmentTime: [
          { required: true, message: '请选择预约时间', trigger: 'change' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7 // 不能选择过去的日期
        }
      }
    }
  },
  methods: {
    // 获取废品类型列表
    getTypeList() {
      this.loading = true
      // this.$http.get('/recycle/recycleType/list', {
      //   params: {
      //     keyword: this.searchForm.keyword
      //   }
      // }).then(response => {
      //   if (response.data.code === 200) {
      //     this.typeList = response.data.data || []
      //   } else {
      //     this.$message.error(response.data.message || '获取废品类型列表失败')
      //   }
      // }).catch(error => {
      //   console.error('获取废品类型列表失败', error)
      //   this.$message.error('获取废品类型列表失败')
      // }).finally(() => {
      //   this.loading = false
      // })
    },
    // 搜索废品类型
    searchTypes() {
      this.getTypeList()
    },
    // 创建订单
    createOrder(type) {
      this.currentType = type
      this.orderForm = {
        weight: 0,
        address: '',
        appointmentTime: '',
        remark: ''
      }
      
      // 获取用户默认地址
      const userId = localStorage.getItem('userId')
      if (userId) {
        this.$http.get('/userService/address/selectAddressByUserId', {
          params: { userId }
        }).then(response => {
          if (response.data.code === 200 && response.data.data.length > 0) {
            // 查找默认地址
            const defaultAddress = response.data.data.find(addr => addr.isDefault === 1)
            if (defaultAddress) {
              this.orderForm.address = defaultAddress.detailedAddress
            } else if (response.data.data.length > 0) {
              // 如果没有默认地址，使用第一个地址
              this.orderForm.address = response.data.data[0].detailedAddress
            }
          }
        }).catch(error => {
          console.error('获取地址失败', error)
        })
      }
      
      this.orderDialogVisible = true
    },
    // 提交订单
    submitOrder() {
      this.$refs.orderForm.validate(valid => {
        if (valid) {
          const userId = localStorage.getItem('userId')
          if (!userId) {
            this.$message.warning('请先登录')
            this.$router.push('/login')
            return
          }
          
          const orderData = {
            userId: userId,
            typeId: this.currentType.id,
            weight: this.orderForm.weight,
            address: this.orderForm.address,
            appointmentTime: this.orderForm.appointmentTime,
            remark: this.orderForm.remark
          }
          
          this.$http.post('/recycle/recyclingOrder/create', orderData).then(response => {
            if (response.data.code === 200) {
              this.$message.success('预约成功')
              this.orderDialogVisible = false
              // 跳转到订单列表页
              this.$router.push('/user/orders')
            } else {
              this.$message.error(response.data.message || '预约失败')
            }
          }).catch(error => {
            console.error('预约失败', error)
            this.$message.error('预约失败，请稍后重试')
          })
        }
      })
    }
  },
  mounted() {
    this.getTypeList()
  }
}
</script>

<style lang="less" scoped>
.user-recycle-type-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;

  .search-area {
    margin-bottom: 20px;
  }

  .type-list {
    .type-card {
      margin-bottom: 20px;

      .type-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        h3 {
          margin: 0;
          font-size: 18px;
        }
      }

      .type-content {
        .description {
          color: #666;
          margin-bottom: 10px;
        }

        .unit-info {
          color: #999;
          font-size: 14px;

          i {
            margin-right: 5px;
          }
        }
      }

      .type-footer {
        margin-top: 15px;
        text-align: center;
      }
    }
  }

  .unit {
    margin-left: 10px;
    color: #606266;
  }
}
</style>